//
//  GiveRiceVC.swift
//  zhonglb_iOS
//
//  Created by lxm on 2021/12/1.
//

import UIKit
import RxRelay
import HandyJSON

class IntegralExchange: ZMViewController, UITextFieldDelegate {
    
    //MARK:--------------------属性--------------------
    var ratio = ZMUtil.fastNilBehavior(type: Double.self)
    // 当前选中的好友
    let info = ZMUtil.fastNilBehavior(type: [String : Any].self)

    // 1 落锤次数 2额度
    var type = 1
    
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var moneyText: UITextField!
        
    @IBOutlet weak var handFee: UILabel!
    
    @IBOutlet weak var topTip: UILabel!
    
    @IBOutlet weak var sureButton: UIButton!
        
    @IBOutlet weak var balance: UILabel!
    
    var loading = XMLoadingView()
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        loading.showInView(fatherView: view)
        setUI()
        addConstraints()
        bindAction()
        loadWallet()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = type == 1 ? "积分换竞购落锤次数" : "积分换出局额度"
        topTip.text = type == 1 ? "兑换次数" : "兑换额度"
        moneyText.delegate = self
        setRightCustomBtn(titleStr: "兑换记录", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 14))
    }
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------

    override func rightBtnClick(sender: UIButton) {
        let vc = IntegralExchangeRecord()
        vc.type = type
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func bindAction() {
        Observable.combineLatest(moneyText.rx.text.orEmpty, info).subscribe(onNext:{ [unowned self] resp in
//            guard let r = self.calculate() else {
//               self.setPayButtonEnable(enable: false)
//                var str = "手续费：\(self.ratio.value ?? 0)%"
//                self.handFee.text = str
//               return
//            }
//            let ok = r.handFee.adding(r.money).compare(r.banlance) == .orderedAscending && resp.1 != nil && resp.2.count == 6
//            self.setPayButtonEnable(enable: ok)
//            var str = "手续费：\(r.handFee.stringValue) (\(r.ratio.stringValue)%)"
//            self.handFee.text = str
            guard let v = Double(resp.0), let dic = resp.1 else {
                self.setPayButtonEnable(enable: false)
                self.handFee.text = "所需积分：0"
                return
            }
            let ratio = JSON(dic)["ratio"].doubleValue
            let amount = JSON(dic)["integral"].doubleValue
            let need = v * ratio
            setPayButtonEnable(enable: need <= amount)
            
            self.handFee.text = "所需积分：\(need.zm.toString(keep: 4))"
        }).disposed(by: disposeBag)
 
        
//        currentUser.subscribe(onNext:{ [unowned self] resp in
//            if let r = resp {
//                self.avatar.zm.setImage(urlStr: r.avatar)
//                self.nickname.text = r.nickname
//                self.showid.text = "手机号：" + r.phone.zm.hidPhone()
//                self.showid.isHidden = false
//            } else {
//                self.showid.isHidden = true
//                self.nickname.text = "选择转账给"
//            }
//        }).disposed(by: disposeBag)
//        
//        wallet.subscribe(onNext:{ [unowned self] resp in
//            if let resp = resp {
//                self.balance.text = "可用余额：" + resp.balance.zm.toString(keep: 4)
//            }
//        }).disposed(by: disposeBag)
//
//        ratio.subscribe(onNext:{ [unowned self] resp in
//            if let resp = resp {
//                self.handFee.text = "手续费：\(resp)%"
//            }
//        }).disposed(by: disposeBag)
        
        info.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else{
                self.balance.text = "-"
                return
            }
            let json = JSON(resp)
            self.balance.text = "当前拥有：\(json["integral"].stringValue)"
        }).disposed(by: disposeBag)
    }

    @IBAction func onSure(_ sender: Any) {
        if !ZMAppShareData.share.safeUserInfo.isTradeOk {
            // 判断是否设置交易密码
            ZMAlertView.show(content: "还未设置交易密码", left: "关闭", right: "马上去设置") {
                
            } onRight: {
                let cls = Swift.type(of: self)
                MineService.shared.tradeSuccessToVC = cls
                let vc = TradeFroget()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            return
        }
        realTransfer()
    }
    
    func realTransfer() {
        guard let v = Double(moneyText.text!), let dic = info.value else {
            return
        }
        let ratio = JSON(dic)["ratio"].doubleValue
        
        CommonService.shared.showPsdInput(title : "确认兑换",
                                          money: "\(Int(v))",
                                          left : "",
                                          center: "所需积分：\((v * ratio).zm.roundingDown(keep: 4))",
                                          right : "",
                                          type: 1,
                                          subTitle: type == 1 ? "次" : "额度") { psd, close in
            // 创建将军令
            ZMToast.showActivity()
//            MineAPI.create_auth_code(["id" : "1","userId":ZMAppShareData.share.safeUserId, "type":typeStr]).rxRequest(type: String.self).flatMapLatest { r ->  Observable<Any?> in
//                // 生成本地将军令
            let pa = ["tradePwd" : psd, "number" : Int(v)] as [String : Any]
            let exchangeApi = self.type == 1 ? VIPMallAPI.exchangeHammer(pa) : VIPMallAPI.exchangeQuato(pa)
            
            exchangeApi.rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
                close(true)
                ZMToast.showToast(title: "兑换成功")
//                self.loadWallet()
//                self.moneyText.text = ""
//                self.moneyText.sendActions(for: .valueChanged)
                self.navigationController?.popViewController(animated: true)
                if let op = optionSuccessBlock {
                    op(nil)
                }
            }, onError: { e in
                close(false)
            }).disposed(by: self.disposeBag)
        }
    }
    
//    func encryptParams() -> String {
//        guard let json = self.transferModel.toJSONString() else {return ""}
//        let after = ZMOcHelper.encrypt(json, key: theKey)
//        return after
//    }
    
    func loadWallet() {
        VIPMallAPI.exchangeRatio(["type" : type]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.info.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    // 将支付按钮设置为可用?
    func setPayButtonEnable(enable : Bool) {
        self.sureButton.isEnabled = enable
        self.sureButton.backgroundColor = enable ? Style.mainColor : UIColor.zm.colorCCCCCC()
    }
    
    //MARK:--------------------delegate--------------------
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text
        let nsOldStr = oldStr! as NSString
        let newStr = nsOldStr.replacingCharacters(in: range, with: string)
        return (newStr.zm.match("\\d{0,10}") || newStr.count == 0)
    }
}

